21. Solutions for Quiz: Practice Debugging

Solution for Quiz: Practice Debugging.

** The code prompts the user for 10 two-digit numbers. It is supposed to then find and print the sum of all of the even numbers among those that were entered. But there is a bug in the code, because when I input a number, I get a TypeError. **

** How can I find the bug in the code and debug it? **

  • I added a print statement to check the datatype of the variable holding the number input by the user. print(type(userInput)). I added this statement after the line
    userinput = input("Enter any number: ").
  • The output showed:

    'class 'str' followed by TypeError: not all arguments converted during string formatting.
  • This meant that the variable userInput had a datatype of a string, but we need the datatype to be int instead. The datatype for userInput needed to be changed to int.
  • To fix the error, I used the built-in function int()to return an integer object from the value input by the user.
    See my solution below:

** Here is my solution:**

user_list = []  
list_sum = 0
for i in range(10):
    userInput = int(input("Enter any number: "))
    try:
        user_list.append(userInput)
        if userInput % 2 == 0:
            list_sum += userInput
    except ValueError:
        print("Incorrect value. That's not an int!")

print("user_list: {}".format(user_list))
print("The sum of the even numbers in user_list is: {}.".format(list_sum))